package org.jeecgframework.core.extend.video;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jeecgframework.core.util.FileUtils;

public class FFMpegConverter implements FLVConverter {
	
	protected static Log logger = LogFactory.getLog(FFMpegConverter.class);
	/**
	 * ffmpeg路径
	 */
	private String ffmpegHome;

	public FFMpegConverter(){
		
	}
	
	public FFMpegConverter(String ffmpegPath){
		this.ffmpegHome = ffmpegPath;
	}
	
	public void convert2Flv(String inputFile, String flvFile) {
		String floder = inputFile.substring(0, inputFile.lastIndexOf("/"));
		File file = new File(floder);
		if(!file.exists()){
			file.mkdirs();
		}
		List<String> commend = new ArrayList<String>();
		commend.add(ffmpegHome);
		commend.add("-i");
		commend.add(inputFile);
		//commend.add("-ar 22050");
		commend.add("-y");
		commend.add("-f");
		commend.add("flv");
		commend.add("-ar");
		commend.add("44100");
		
		commend.add(flvFile);
		try {
			logger.info("视频转化开始...");
			ProcessBuilder builder = new ProcessBuilder(commend);
			builder.redirectErrorStream(true);
			Process process = builder.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String tmp = null;
			while ((tmp = br.readLine()) != null) {
				logger.info(tmp);
			}
			process.waitFor();
			logger.info("视频转化结束...");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("视频:"+inputFile+",转化为Flv格式失败!",e);
		}
	}

	public void convert2Flv(String inputFile) {
		String flvFile = FileUtils.getFilePrefix(inputFile)+".flv";
		convert2Flv(inputFile, flvFile);
	}
	
	public String getFfmpegHome() {
		return ffmpegHome;
	}

	public void setFfmpegHome(String ffmpegHome) {
		this.ffmpegHome = ffmpegHome;
	}

	
	public static void main(String[] args) {
		FLVConverter flvc = new FFMpegConverter("E:\\workspace\\self\\LearnOnline\\WebRoot\\video/ffmpeg/bin/ffmpeg.exe");
		flvc.convert2Flv("d:/c.avi", "d:/b.flv");
	}
}
